<?php
/*
 * @Author: CHINAKAIYUAN<sunkaiyuan@namenode.cn>
 * @Date: 2022-02-02 19:42:06
 * @LastEditTime: 2023-10-06 10:29:16
 * @LastEditors: 孙开源 && sunkaiyuan@namenode.cn
 * @Description: 
 */

namespace App\Repositories;

use App\Models\ProBom;

class ProBomRepository extends Repositories
    {
    public $relation_models = ["material", "creator", 'updator', 'details' => ["material", 'point_stick', 'glue'], 'status', 'craft_category'];
    public function boot(ProBom $model)
        {
        $this->model = $model;
        }
    public function fuzzySearch($value)
        {
        $value = trim($value);
        $this->where(function ($query) use ($value)
            {
            $query->orWhere("name", "like", "%{$value}%");
            $query->orWhere("code", "like", "%{$value}%");
            });
        }
    protected function validate($data)
        {
        $data['name'] = trim($data['name']);
        if (isEmpty($data['name'])) {
            fail("工艺名必填");
            }
        else if (is_numeric($data['id'] ?? "") && $data['id'] > 0) {
            $gdata = $this->where("id", "<>", $data['id']);
            }
        $gdata = $this->whereName(trim($data['name']))->first();
        if ($gdata)
            fail("工艺与{$gdata['name']}工艺相同！不可重复！");

        array_filter($data['details'] ?? [], function ($v)
            {
            if (isEmpty($v['point_stick_id'] ?? "")) {
                fail("点棍必填！");
                }
            if (isEmpty($v['rate'] ?? "")) {
                fail("辅料比例必填");
                }
            if (isEmpty($v['glue_id'] ?? "")) {
                fail("胶水必填！");
                }
            });
        return $this;
        }
    }